//
//  HMTabBar.swift
//  WeiBo
//
//  Created by Feng on 2017/6/4.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

//设置代理
protocol HMTabBarDelegate: NSObjectProtocol
{
    func composeDelegateBack()
}

class HMTabBar: UITabBar {

    //定义要执行的闭包
    var composeCallBack: (() -> ())?
    
    //定义代理属性
    weak var hmDelegate: HMTabBarDelegate?
    
    //MARK: --懒加载控件
    private lazy var composeButton: UIButton =
    {
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //设置大小
        button.sizeToFit()
        
        //添加按钮点击事件
        button.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
        
        return button
    }()
    
    //按钮点击方法
    //swift是编译型语言,加了private之后,在编译时就找不到composeButtonClick方法,加上@objc 之后,让程序在运行时,动态添加此方法
    @objc private func composeButtonClick()
    {
        //? 如果是nil,就返回nil,否则就执行闭包
        composeCallBack?()
        
        //执行代理方法
//        self.hmDelegate?.composeDelegateBack()
    }
    
    //创建视图
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //布局方法
    func setupUI()
    {
        self.addSubview(composeButton)
        
        //设置背景色,解决push时的黑影效果
        self.backgroundImage = UIImage(named: "tabbar_background")
    }
    
    //设置composeButton的位置
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeButton.centerX = self.frame.size.width * 0.5
        composeButton.centerY = self.frame.size.height * 0.5
        
        //设置tabBar上4个按钮的间距
        let buttonWidth = self.width / 5
        
        var index = 0
        
        for subview in subviews
        {
            if subview.isKind(of: NSClassFromString("UITabBarButton")!)
            {
                //设置x坐标
                subview.x = buttonWidth * CGFloat(index)
                
                subview.width = buttonWidth
                
                index += 1
            }
            //第三个按钮,间距为2倍buttonWidth
            if index == 2
            {
                index += 1
            }
        }
    }
}
